<template>
  <div class="map-box" ref="mapBox"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import 'echarts/theme/macarons'
import 'echarts/extension/bmap/bmap'
import { loadBMap } from '@/utils/map'
import { useAutoImport } from '@/hooks/autoImport'
const { onMounted, nextTick, ref, API } = useAutoImport()

//原生地图实现
////地图实例
//let map = null
////地图dom元素
//const mapBox = ref(null)
////绘制点
//const createPoint = (map, { lan, lat, item }) => {
//  let point = new BMapGL.Point(lan, lat)
//  //创建标注
//  let marker = new BMapGL.Marker3D(point, 0, {
//    size: 18,
//    shape: 1,
//    fillColor: '#be8026',
//    fillOpacity: 0.8,
//  })
//  map.addOverlay(marker)
//  // 详细信息
//  let info = new BMapGL.InfoWindow(
//    `<div class="map-device-info">
//            <p>设备名称：<span>${item.deviceName}</span></p>
//            <p>设备编号：${item.serialNumber}</p>
//            <p>所在地址：${item.networkAddress}</p>
//        </div>`,
//    {
//      width: 200,
//      height: 100,
//      title: `<h2 class="map-device-info">设备详细信息</h2>`,
//    },
//  )
//  marker.addEventListener('mouseover', () => map.openInfoWindow(info, point))
//  marker.addEventListener('mouseout', () => map.closeInfoWindow())
//}
//
//onMounted(() => {
//  if (!mapBox.value) return
//  map = new BMapGL.Map(mapBox.value) // 创建地图实例
//  let point = new BMapGL.Point(103.38861, 35.86166) // 创建点坐标
//  map.centerAndZoom(point, 5) // 初始化地图，设置中心点坐标和地图级别
//  map.enableScrollWheelZoom(true) //开启鼠标滚轮缩放
//})
//
//onBeforeMount(async () => {
//  try {
//    let { code, rows } = await API.home.reqDeviceAll()
//    if (+code === 200 && map) {
//      rows.forEach((item) => {
//        createPoint(map, {
//          lan: item.longitude,
//          lat: item.latitude,
//          item,
//        })
//      })
//    }
//  } catch (_) {}
//})

const mapBox = ref(null)
let deviceList = ref([])
let deviceCount = ref(0)

const getAllDevice = async () => {
  let { code, rows, total } = await API.home.reqDeviceAll()
  if (+code === 200) {
    deviceList.value = rows
    deviceCount.value = total
    initMap()
  }
}

const initMap = () => {
  nextTick(async () => {
    await loadBMap()
    getMap()
  })
}

onMounted(() => {
  getAllDevice()
})

/** 地图 */
const getMap = () => {
  const myChart = echarts.init(mapBox.value)
  let option

  // 格式化数据
  let convertData = function (data, status) {
    let res = []
    for (let i = 0; i < data.length; i++) {
      let geoCoord = [data[i].longitude, data[i].latitude]
      if (geoCoord && data[i].status == status) {
        res.push({
          name: data[i].deviceName,
          value: geoCoord,
          serialNumber: data[i].serialNumber,
          status: data[i].status,
          isShadow: data[i].isShadow,
          firmwareVersion: data[i].firmwareVersion,
          networkAddress: data[i].networkAddress,
          productName: data[i].productName,
          activeTime: data[i].activeTime == null ? '' : data[i].activeTime,
          deviceId: data[i].deviceId,
          serialNumber: data[i].serialNumber,
          locationWay: data[i].locationWay,
        })
      }
    }
    return res
  }
  option = {
    title: {
      text:
        '设备分布（在线数 ' +
        deviceList.value.filter((x) => x.status == 3).length +
        '）',
      subtext: 'wumei-smart open source living iot platform',
      sublink: 'https://iot.wumei.live',
      target: '_blank',
      textStyle: {
        color: '#333',
        textBorderColor: '#fff',
        textBorderWidth: 10,
      },
      top: 10,
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        var htmlStr = '<div style="padding:5px;line-height:28px;">'
        htmlStr +=
          "设备名称： <span style='color:#409EFF'>" +
          params.data.name +
          '</span><br />'
        htmlStr += '设备编号： ' + params.data.serialNumber + '<br />'
        htmlStr += '设备状态： '
        if (params.data.status == 1) {
          htmlStr += "<span style='color:#E6A23C'>未激活</span>" + '<br />'
        } else if (params.data.status == 2) {
          htmlStr += "<span style='color:#F56C6C'>禁用</span>" + '<br />'
        } else if (params.data.status == 3) {
          htmlStr += "<span style='color:#67C23A'>在线</span>" + '<br />'
        } else if (params.data.status == 4) {
          htmlStr += "<span style='color:#909399'>离线</span>" + '<br />'
        }
        if (params.data.isShadow == 1) {
          htmlStr +=
            '设备影子： ' + "<span style='color:#67C23A'>启用</span>" + '<br />'
        } else {
          htmlStr +=
            '设备影子： ' +
            "<span style='color:#909399'>未启用</span>" +
            '<br />'
        }
        htmlStr += '产品名称： ' + params.data.productName + '<br />'
        htmlStr +=
          '固件版本： Version ' + params.data.firmwareVersion + '<br />'
        htmlStr += '激活时间： ' + params.data.activeTime + '<br />'
        htmlStr += '定位方式： '
        if (params.data.locationWay == 1) {
          htmlStr += '自动定位' + '<br />'
        } else if (params.data.locationWay == 2) {
          htmlStr += '设备定位' + '<br />'
        } else if (params.data.locationWay == 3) {
          htmlStr += '自定义位置' + '<br />'
        } else {
          htmlStr += '未知' + '<br />'
        }
        htmlStr += '所在地址： ' + params.data.networkAddress + '<br />'
        htmlStr += '</div>'
        return htmlStr
      },
    },
    bmap: {
      center: [143, 28],
      zoom: 5,
      roam: true,
      mapStyle: {
        styleJson: [
          {
            featureType: 'water',
            elementType: 'all',
            stylers: {
              color: '#a0cfff',
            },
          },
          {
            featureType: 'land',
            elementType: 'all',
            stylers: {
              color: '#fafafa', // #fffff8 淡黄色
            },
          },
          {
            featureType: 'railway',
            elementType: 'all',
            stylers: {
              visibility: 'off',
            },
          },
          {
            featureType: 'highway',
            elementType: 'all',
            stylers: {
              color: '#fdfdfd',
            },
          },
          {
            featureType: 'highway',
            elementType: 'labels',
            stylers: {
              visibility: 'off',
            },
          },
          {
            featureType: 'arterial',
            elementType: 'geometry',
            stylers: {
              color: '#fefefe',
            },
          },
          {
            featureType: 'arterial',
            elementType: 'geometry.fill',
            stylers: {
              color: '#fefefe',
            },
          },
          {
            featureType: 'poi',
            elementType: 'all',
            stylers: {
              visibility: 'off',
            },
          },
          {
            featureType: 'green',
            elementType: 'all',
            stylers: {
              visibility: 'off',
            },
          },
          {
            featureType: 'subway',
            elementType: 'all',
            stylers: {
              visibility: 'off',
            },
          },
          {
            featureType: 'manmade',
            elementType: 'all',
            stylers: {
              color: '#d1d1d1',
            },
          },
          {
            featureType: 'local',
            elementType: 'all',
            stylers: {
              color: '#d1d1d1',
            },
          },
          {
            featureType: 'arterial',
            elementType: 'labels',
            stylers: {
              visibility: 'off',
            },
          },
          {
            featureType: 'boundary',
            elementType: 'all',
            stylers: {
              color: '#999999',
            },
          },
          {
            featureType: 'building',
            elementType: 'all',
            stylers: {
              color: '#d1d1d1',
            },
          },
          {
            featureType: 'label',
            elementType: 'labels.text.fill',
            stylers: {
              color: '#999999',
            },
          },
        ],
      },
    },
    series: [
      {
        type: 'scatter',
        coordinateSystem: 'bmap',
        data: convertData(deviceList.value, 1),
        symbolSize: 15,
        itemStyle: {
          color: '#E6A23C',
        },
      },
      {
        type: 'scatter',
        coordinateSystem: 'bmap',
        data: convertData(deviceList.value, 2),
        symbolSize: 15,
        itemStyle: {
          color: '#F56C6C',
        },
      },
      {
        type: 'scatter',
        coordinateSystem: 'bmap',
        data: convertData(deviceList.value, 4),
        symbolSize: 15,
        itemStyle: {
          color: '#909399',
        },
      },
      {
        type: 'effectScatter',
        coordinateSystem: 'bmap',
        data: convertData(deviceList.value, 3),
        symbolSize: 15,
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
          scale: 5,
        },
        label: {
          formatter: '{b}',
          position: 'right',
          show: false,
        },
        itemStyle: {
          color: '#67C23A',
          shadowBlur: 100,
          shadowColor: '#333',
        },
        zlevel: 1,
      },
    ],
  }

  option && myChart.setOption(option)
}
</script>
